package com.sharding5.mybatisplus.seata.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sharding5.mybatisplus.seata.mapper.GoodsMapper;
import com.sharding5.mybatisplus.seata.mapper.OrderMapper;
import com.sharding5.mybatisplus.seata.pojo.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.seata.core.context.RootContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/order")
public class OrderController {
    private static final String SUCCESS = "SUCCESS";
    private static final String FAIL = "FAIL";

    private final OrderMapper orderMapper;
    private final GoodsMapper goodsMapper;

    /**
     * 订单列表
     *
     * @param pageNum
     */
    @GetMapping("/list")
    public Object list(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.selectAllOrder();
        PageInfo<Order> pageInfo = new PageInfo<>(orderList);
        return pageInfo;
    }

    /**
     * 添加订单
     *
     * @param orderId
     * @param isFail
     */
    @GlobalTransactional(timeoutMills = 30000, rollbackFor = Exception.class)
    @Transactional(timeout = 30, rollbackFor = Exception.class)
    @GetMapping("/add/{orderId}/{goodsId}/{count}")
    public String addOrder(@PathVariable(value = "orderId", required = true) Long orderId,
                           @PathVariable(value = "goodsId", required = true) Long goodsId,
                           @PathVariable(value = "count", required = true) Integer count,
                           @RequestParam(value = "isFail", required = true, defaultValue = "0") int isFail) {
        String goodsName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Order order = new Order();
        order.setOrderId(orderId);
        order.setGoodsName(goodsName);
        int orderResult = orderMapper.insertOneOrder(order);
        log.info("新增订单：{}，结果：{}", JSON.toJSONString(order), orderResult);

        int goodsResult = goodsMapper.updateGoodsStock(goodsId, -count);
        log.info("修改库存结果：{}", goodsResult);

        if (isFail == 1) {
            int divide = 0;
            int resul = 100 / divide;
        }
        if (goodsResult > 0) {
            return SUCCESS;
        } else {
            return FAIL;
        }
    }

    /**
     * 添加订单，rest 方式
     *
     * @param orderId
     * @param isFail
     */
    @GlobalTransactional(timeoutMills = 30000, rollbackFor = Exception.class)
    @Transactional(timeout = 30, rollbackFor = Exception.class)
    @GetMapping("/addRest/{orderId}/{goodsId}/{count}")
    public String addOrderRest(@PathVariable(value = "orderId", required = true) Long orderId,
                               @PathVariable(value = "goodsId", required = true) Long goodsId,
                               @PathVariable(value = "count", required = true) Integer count,
                               @RequestParam(value = "isFail", required = true, defaultValue = "0") int isFail) {
        String goodsName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Order order = new Order();
        order.setOrderId(orderId);
        order.setGoodsName(goodsName);
        int orderResult = orderMapper.insertOneOrder(order);
        log.info("新增订单：{}，结果：{}", JSON.toJSONString(order), orderResult);

        RestTemplate restTemplate = new RestTemplate();
        String xid = RootContext.getXID();
        System.out.println("xid before send:" + xid);
        HttpHeaders headers = new HttpHeaders();
        headers.add(RootContext.KEY_XID, xid);
        String updateStockUrl = "http://127.0.0.1:8888/goods/stock/" + goodsId + "/" + (-count);
        String goodsResult = restTemplate.postForObject(updateStockUrl, new HttpEntity<String>(headers), String.class);
        log.info("修改库存：{}，结果：{}", updateStockUrl, goodsResult);
        if (!SUCCESS.equals(goodsResult)) {
            throw new RuntimeException();
        }

        if (isFail == 1) {
            int divide = 0;
            int resul = 100 / divide;
        }
        return SUCCESS;
    }
}

